import com.sun.source.tree.Tree;

/**
 * @Author: Lenovo
 * @Date: 2024/7/28 17:43
 * @description:
 */
public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;
    public void insert(int key){
        if (root == null){
            root = new TreeNode(key);
            return;
        }
        TreeNode parnet = null;
        TreeNode cur = root;
        TreeNode node = new TreeNode(key);
        while (cur != null){
            if (cur.val > key){
                parnet = cur;
                cur = cur.left;
            }else if (cur.val < key){
                parnet = cur;
                cur = cur.right;
            }else {
                return;
            }
        }
        if (parnet.val > key){
            parnet.left = node;
        }else {
           parnet.right = node;
       }
    }
    public TreeNode search(int key){
        TreeNode cur = root;
        while (cur != null){
            if (cur.val > key){
                cur = cur.left;
            }else if (cur.val < key){
                cur = cur.right;
            }else {
                return cur;
            }
        }
        return null;
    }
    public void remove(int key){
        TreeNode parent = null;
        TreeNode cur = root;
        while (cur != null){
            if (cur.val > key){
                parent = cur;
                cur = cur.left;
            }else if (cur.val < key){
                parent = cur;
                cur = cur.right;
            }else {
                removeNode(parent,cur);
                return;
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        if (cur.left == null){
           if (cur == root){
               root = root.right;
           }else if(cur == parent.left){
               parent.left = cur.right;
           }else if (cur == parent.right){
               parent.right = cur.right;
           }
        } else if (cur.right == null) {
            if (cur == root){
                root = root.right;
            } else if (cur == parent.left) {
                parent.left = cur.left;
            }else if (cur == parent.right){
                parent.right = cur.left;
            }
        } else {
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while (target != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (targetParent.left == target){
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }
        }
    }

}
